<?php

// Session Design Improvements: Move (array) $Sessions -> $System Variable (Ease of Access, Security, Design Overview);

/* Design

 Login: Vaildate, md5, logout login keys, Set Cookie after request
 
 */
        
class Session {
	
	private $sid = 0;
	private $uid = 0;
	private $ipaddress;
	private $useragent;

	public function __construct() {
		
		global $System, $db;
		
		$this->ipaddress = $this->get_ip();
		
		$this->useragent = $_SERVER['HTTP_USER_AGENT'];
		
		// Do we, have a vaild Session >:D
		
		if(isset($System->Cookies['sid'])) {
			
			$this->sid = $db->escape_string($System->Cookie['sid']);
			
			$db->query("SELECT * FROM `Sessions` WHERE `sid` = '{$this->sid}' AND `ip` = '{$this->ipaddress}'");
			
			$Query = $db->fetch_array();
			
			if($Query['sid']) {
				
				$this->uid = $Query['uid'];

			}
			
		}
		
		// Vaild Session ! Load Users !!
		
		if($System->cookie['User'] && $System->cookie['sid'] && $System->cookie['uid']) {
				
			$Logon = explode("_", $System->cookie['user'], 2);
				
			$this->Login($Logon[0], $Logon[1]);
				
		}
			
		if(!$this->Session['sid'] || !$this->Session['data']) {
				
			$this->Login_Guest();
				
		}
			
	}
	
	public function login($User, $Password) {
		
		global $System, $db;
		
		// Guessing Either Login.php, Cookie, Or Session has logged us in !
		// Login.php : Vailidate Input, hash password etc
		// Check Username / Password
		// Setup Local Settings
		// Woot!
		
	}
	
	public function login_guest() {
		
		// Load Guest Usergroup etc..
		
	}
	
	
	public get_real_ip() {
		
		if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
		
			return $_SERVER['HTTP_X_FORWARDED_FOR'];
		
		}elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
		
			return $_SERVER['HTTP_CLIENT_IP'];
		 
		}else{ 
		
			return $_SERVER['REMOTE_ADDR'];
			
		}
		
	}
	
	public function bakeCookie($name, $data, $expire) {
		
		global $System, $Config;
		
		if(!$Config->Cookie['Path']) {
			
			$Config->Cookie['Path'] = "/";
			
		}
		
		if($expires == null || $expires = "") {
			
			$expires = NOW + (60*60*24*365);
			
		}else{
			
			$expires = NOW + intval($expires);
		
		}
		
		$Cookie = "Set-Cookie: {$name} = " . urlencode($data) . "; expires = {$expires}; path = {$Config->Cookie['Path']}; domain={$Config->Cookie['domain']}";
		
		$System->Cookie = $data;
		
		header($cookie);
		
		
	}


		
			
		